import {
  Card,
  Col,
  Form,
  Row,
  Select,
  Input,
  Button,
  Table,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import {
  getHospitalSearchParamsType,
  getHospitalListContentType,
  getHospitalListItemType,
  getProvinceListType,
  getCityType,
} from "@/api/hospital/model/hospitalListType";
import {
  changeHospitalStatus,
  getCityOrStrictRequest,
  getHospitalListRequest,
  getProvinceListRequest,
} from "@/api/hospital/hospitalList";
import { useNavigate } from "react-router-dom";

export default function HospitalList() {
  const { Option } = Select;
  const navigate = useNavigate();
  const [form] = Form.useForm();
  //定义页面是否加载完成
  const [isLoading, setIsLoading] = useState(false);
  //定义当前页的状态
  const [page, setPage] = useState(1);
  //定义每页显示数量的状态
  const [limit, setLimit] = useState(4);
  //定义医院总数
  const [total, setTotal] = useState(0);
  //定义params参数
  const [searchParams, setSearchParams] = useState<getHospitalSearchParamsType>(
    {}
  );
  //定义请求的数据
  const [reqData, setReqData] = useState<getHospitalListContentType>([]);
  //定义省份
  const [province, setProvince] = useState<getProvinceListType>([]);
  //定义市
  const [city, setCity] = useState<getCityType>([]);
  //定义区县
  const [strick, setStrick] = useState<getCityType>([]);
  //定义医院类型
  const [hospitalStyle, setHospitalStyle] = useState<getCityType>([]);
  //设置重新渲染页面
  const [reRender, setReRender] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    const getHospitalList = async () => {
      const result = await getHospitalListRequest(page, limit, searchParams);
      // console.log(result.content);
      // console.log(result);
      setIsLoading(false);
      setReqData(result.content);
      setTotal(result.totalElements);
    };
    getHospitalList();
  }, [page, limit, searchParams, reRender]);

  //初始化的时候获取省
  useEffect(() => {
    const getProvinceList = async () => {
      const result = await getProvinceListRequest();
      // console.log(result);
      setProvince(result);
    };
    getProvinceList();
  }, []);
  //初始化的时候获取医院类型
  useEffect(() => {
    const getHospitalStyleHandle = async () => {
      const result = await getCityOrStrictRequest("10000");
      // console.log(result);
      setHospitalStyle(result);
    };
    getHospitalStyleHandle();
  }, []);
  //获取市
  const getCityHandle = async (id: string) => {
    // console.log(a,b);//第一个参数市id  第二个参数市data
    const result = await getCityOrStrictRequest(id);
    // console.log(result);
    setCity(result);
    // 选择省的时候把市和县区的value清空
    form.setFieldsValue({ cityCode: null, districtCode: null });
    // 清空县区的下拉
    setStrick([]);
  };
  //获取区县
  const getStrickHandle = async (id: string) => {
    const result = await getCityOrStrictRequest(id);
    // console.log(result);
    setStrick(result);
    form.setFieldsValue({ districtCode: null });
  };

  //提交表单,改变params参数，重新渲染页面，获取查询结果
  const finishHospitalHandle = (params: getHospitalSearchParamsType) => {
    setSearchParams(params);
  };
  //点击清空按钮事件
  const clearHospitalListHandle = () => {
    setSearchParams({});
  };
  //点击查看按钮路由跳转
  const viewHospitalDetailHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitaldetail/${id}`);
    };
  };
  //点击改变状态
  const changeHospitalStatusHandle = (id: string, status: 0 | 1) => {
    return async () => {
      await changeHospitalStatus(id, status);
      message.success("修改状态成功！");
      setReRender(!reRender);
    };
  };

  const columns = [
    {
      title: "序号",
      with: 60,
      dataIndex: "index",
      render(_: any, __: any, c: any) {
        return c + 1;
      },
    },
    {
      title: "医院logo",
      render(_: any, data: getHospitalListItemType) {
        return (
          <img
            width={100}
            src={`data:img/jpeg;base64,${data.logoData}`}
            alt=""
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: getHospitalListItemType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: getHospitalListItemType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: getHospitalListItemType) {
        return data.status === 0 ? "离线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      fixed: "right" as "right",
      with: 90,
      render(_: any, data: getHospitalListItemType) {
        return (
          <div>
            <Button type="primary" onClick={viewHospitalDetailHandle(data.id)}>
              查看
            </Button>
            <Button type="primary">排班</Button>
            <Button
              type="primary"
              onClick={changeHospitalStatusHandle(
                data.id,
                data.status === 0 ? 1 : 0
              )}
            >
              {data.status === 0 ? "上线" : "离线"}
            </Button>
          </div>
        );
      },
    },
  ];

  const pageChangeHandle = (page: number, limit: number) => {
    // 当前页数，和每页可以显示多少条
    setPage(page);
    setLimit(limit);
  };

  return (
    <div>
      <Card>
        <Form form={form} onFinish={finishHospitalHandle}>
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select placeholder="请选择省" onChange={getCityHandle}>
                  {province.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select placeholder="请选择市" onChange={getStrickHandle}>
                  {city.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区">
                  {strick.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型">
                  {hospitalStyle.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态">
                  <Option value={1}>上线</Option>
                  <Option value={0}>离线</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ marginRight: "15px" }}
                  icon={<SearchOutlined />}
                >
                  查询
                </Button>
                <Button
                  type="default"
                  htmlType="reset"
                  onClick={clearHospitalListHandle}
                >
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table
          columns={columns}
          dataSource={reqData}
          scroll={{ x: 1100 }}
          rowKey={"id"}
          bordered
          pagination={{
            // 当前页数
            current: page,
            // 每页条数
            pageSize: limit,
            // 数据总数
            total: total,
            // 是否可以快速跳转至某页
            showQuickJumper: true,
            // pageSizeOptions指定每页可以显示多少条
            pageSizeOptions: [4, 8, 12],
            // 是否展示 pageSize 切换器
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange: pageChangeHandle,
          }}
          //页面是否加载中
          loading={isLoading}
        />
      </Card>
    </div>
  );
}
